﻿using Microsoft.Extensions.Logging;
using net.xBei.Filters;
using net.xBei.Helper;
using net.xBei.WebApi.Filters;
using net.xBei.WebApi.Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using xBei.Redis.Extension;

namespace net.xBei.Repository {
    /// <summary>
    /// API执行时间计时器
    /// </summary>
    public class ApiTimerService : EventQueueBackgroundService<ApiTimerFilter.EventData> {
        private readonly RedisClient redisClient;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="redisClient"></param>
        /// <param name="eventService"></param>
        /// <param name="logger"></param>
        public ApiTimerService(RedisClient redisClient,
                               EventService eventService,
                               ILogger<ApiTimerFilter> logger) : base(eventService, logger) {
            this.redisClient = redisClient;
        }
        /// <inheritdoc/>
        public override string Name => ApiTimerFilter.EventKey;
        /// <inheritdoc/>
        public override string EventKey => ApiTimerFilter.EventKey;
        /// <inheritdoc/>
        protected override int MillisecondsDelay => 0;
        /// <inheritdoc/>
        protected override async Task FireAsync(EventData<ApiTimerFilter.EventData> eventData) {
            var data = eventData.Data;
            var key = $"API-LOGS:{data.Service}:{data.Controller}:{data.Action}";
            var miniKey = $"{key}:MINI";
            var maxKey = $"{key}:MAX";
            var listKey = $"{key}:LIST:{DateTime.UtcNow:yyyy-MM-dd}";
            await redisClient.IncrementAsync($"{key}:COUNT");
            var miniTime = (double)await redisClient.GetValueAsync(miniKey, double.MaxValue);
            if (miniTime > data.Elapsed.TotalMilliseconds) {
                await redisClient.SetValueAsync(miniKey, data.Elapsed.TotalMilliseconds);
            }
            var maxTime = (double)await redisClient.GetValueAsync(maxKey, double.MinValue);
            if (maxTime < data.Elapsed.TotalMilliseconds) {
                await redisClient.SetValueAsync(maxKey, data.Elapsed.TotalMilliseconds);
            }
            await redisClient.EnqueueAsync(listKey, data.ToJson(), 30 * 24 * 36400);
        }
    }
}
